﻿var insertMode = true;
var AlreadyExistsMessage;
var ExceedesStockMessage;

$(function () {

    $.datepicker.setDefaults($.datepicker.regional["es"]);

    $("#_creationDate").datepicker({
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        yearRange: "-100:+10",
        onSelect: function (dateText, inst) {
            var date = $(this).datepicker('getDate'),
            day = date.getDate(),
            month = date.getMonth() + 1,
            year = date.getFullYear();
            $("#CreationDate").val(month + "-" + day + "-" + year)
        }
    });

    $("#Save").click(function () {
        $("#DeliveryNoteContent").mask("Cargando...");
        var index = 0;
        $("tr[id^='rowItem_']").each(function () {
            var rowIndex = $(this).attr("id").substr($(this).attr("id").indexOf("_") + 1);
            if ($("#Quantity_" + rowIndex).val() > 0) {
                $("<input/>").attr("type", "hidden")
                     .attr("id", "DeliveryNoteReplacements_" + index + "ReplacementID")
                     .attr("name", "DeliveryNoteReplacements[" + index + "].ReplacementID")
                     .val($("#ReplacementID_" + rowIndex).val())
                     .appendTo("#ItemTable");

                $("<input/>").attr("type", "hidden")
                     .attr("id", "DeliveryNoteReplacements_" + index + "Quantity")
                     .attr("name", "DeliveryNoteReplacements[" + index + "].Quantity")
                     .val($("#Quantity_" + rowIndex).val())
                     .appendTo("#ItemTable");

                $("<input/>").attr("type", "hidden")
                     .attr("id", "DeliveryNoteReplacements_" + index + "UnitPrice")
                     .attr("name", "DeliveryNoteReplacements[" + index + "].UnitPrice")
                     .val($("#UnitPrice_" + rowIndex).val())
                     .appendTo("#ItemTable");

                $("<input/>").attr("type", "hidden")
                     .attr("id", "DeliveryNoteReplacements_" + index + "TotalPrice")
                     .attr("name", "DeliveryNoteReplacements[" + index + "].TotalPrice")
                     .val($("#TotalPrice_" + rowIndex).val())
                     .appendTo("#ItemTable");
                index++;
            }
        });
    });

    $("#Cancel").click(function () {
        window.location.href = $Url.resolve("~/DeliveryNote/Index");
    });

    $("#CompanyName").autocomplete({
        minLength: 1,
        delay: 0,
        source: function (request, response) {
            $.ajax({
                url: $Url.resolve("~/Customer/GetCustomersByBusinessUnitID"),
                dataType: "json",
                data: { sortColumn: 'CompanyName', companyName: $("#CompanyName").val() },
                success: function (customers) {
                    response($.map(customers, function (customer) {
                        return { label: customer.CompanyName, value: customer.CustomerID }
                    }));
                }
            });
        },
        select: function (event, ui) {
            $("#CompanyName").val(ui.item.label);
            $("#CustomerID").val(ui.item.value);
            //$("#CustomerID").change();
            return false;
        },
        change: function (event, ui) {
            if (ui.item == null) {
                $("#CompanyName").val("");
                $("#CustomerID").val("");
                //$("#CustomerID").change();
            }
            return false;
        }
    });

    $("#ItemName").autocomplete({
        minLength: 1,
        delay: 0,
        source: function (request, response) {
            $.ajax({
                url: $Url.resolve("~/Replacement/GetReplacementsByBusinessUnitIDByFilter"),
                dataType: "json",
                data: { filter: $("#ItemName").val() },
                success: function (replacements) {
                    response($.map(replacements, function (replacement) {
                        return { label: replacement.Name, value: replacement.ReplacementID }
                    }));
                }
            });
        },
        select: function (event, ui) {
            $("#ItemName").val(ui.item.label);
            $("#ItemID").val(ui.item.value);
            return false;
        },
        change: function (event, ui) {
            if (ui.item == null) {
                $("#ItemName").val("");
                $("#ItemID").val("");
                //                $("#AddItem").prop("disabled", true);
            }
            //             else {
            //                $("#AddItem").prop("disabled", false);
            //            }
            return false;
        }
    });

    $("#AddItem").live("click", function () {
        if ($("#ItemID").val() != "") {

            $.ajax({
                url: $Url.resolve("~/Replacement/GetReplacementByID"),
                dataType: "json",
                data: { id: $("#ItemID").val() },
                success: function (replacement) {
                    var exists = false;
                    $("[id*='ReplacementID_']").each(function () {
                        if ($(this).val() == replacement.ReplacementID) {
                            exists = true
                        }
                    });
                    if (!exists) {
                        $("#ItemTable").append("<tr id='rowItem_" + columnIndex + "' class='detail'>" +
                                               "<td id='imgTD_" + columnIndex + "'>" +
                                                   "<input type='hidden' value='" + replacement.ReplacementID + "' id='ReplacementID_" + columnIndex + "' />" +
                                                   "<input type='hidden' value='" + replacement.Stock + "' id='Stock_" + columnIndex + "' />" +
                                                   "<img src='../../Content/Images/cross.png' onclick='DeleteRow(" + columnIndex + ")'/>" +
                                               "</td>" +
                                               "<td>" +
                                                   "<input type='text' value='0' id='Quantity_" + columnIndex + "' onchange='ModifyPrice(" + columnIndex + ")' />" +
                                               "</td>" +
                                               "<td>" +
                                                   replacement.Name +
                                               "</td>" +
                                               "<td>" +
                                                   "<input type='text' value='" + replacement.PublicPrice + "' id='UnitPrice_" + columnIndex + "' onchange='UnitPrice_Change(this, " + columnIndex + " )' />" +
                                               "</td>" +
                                               "<td>" +
                                                   "<input readonly='readonly' type='text' value='0' id='TotalPrice_" + columnIndex + "' />" +
                                                "</td>" +
                                            "</tr>");
                        columnIndex++;
                    } else {
                        alert(AlreadyExistsMessage);
                    }
                }
            });
        }
    });

    Custom.init();
});

function DeleteRow(rowIndex) {
    $("#rowItem_" + rowIndex).remove();
    CalculateTotalPrice();
}

function ModifyPrice(rowIndex) {
    if (CheckStock(rowIndex)) {
        var quantity = $("#Quantity_" + rowIndex).val();
        var unitPrice = $("#UnitPrice_" + rowIndex).val();
        var totalPrice = Math.round((unitPrice * quantity * 100)) / 100;
        $("#TotalPrice_" + rowIndex).val(totalPrice);
        CalculateTotalPrice();
    } else {
        alert(ExceedesStockMessage);
        $("#Quantity_" + rowIndex).val("0");
        $("#Quantity_" + rowIndex).change();
    }
}

function CheckStock(rowIndex) {
    if (parseInt($("#Quantity_" + rowIndex).val()) > parseInt($("#Stock_" + rowIndex).val()))
        return false;
    else
        return true;
}


function UnitPrice_Change(obj, rowIndex) {
    if (obj.value.indexOf(",") > -1) {
        obj.value = obj.value.replace(",", ".");
        $(obj).trigger('change');
        return false;
    }
    try {
        var newValue = Math.round((obj.value * 100)) / 100;
        if (obj.value != newValue) {
            obj.value = newValue;
            $(obj).trigger('change');
            return false;
        }

    }
    catch (err) {
        obj.value = "";
    }
    ModifyPrice(rowIndex);
}

function CalculateTotalPrice() {
    var totalPrice = 0;
    $("[id*='TotalPrice']").each(function () {
        totalPrice += parseFloat($(this).val());
    });
    totalPrice = Math.round((totalPrice * 100)) / 100
    $("#DeliveryNote_Total_Price").text(totalPrice);

}

function submitCompleted(content) {
    $("#DeliveryNoteContent").unmask();
    window.location.href = $Url.resolve("~/DeliveryNote/Index");
}